package com.mocha.test.common;

import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * 扩展方法统计方法执行时间
 */
public class TimingExtension implements BeforeTestExecutionCallback,AfterTestExecutionCallback {

    private static final Logger logger = LoggerFactory.getLogger(TimingExtension.class);

    private static final String START_TIME = "start time";

    @Override
    public void afterTestExecution(ExtensionContext extensionContext) throws Exception {

        Method testMethod = extensionContext.getRequiredTestMethod();
        long start = getStore(extensionContext).remove(START_TIME, long.class);
        long duration = System.currentTimeMillis() - start;
        logger.info(String.format("Method [%s] took %s ms",testMethod.getName(),duration));

    }

    @Override
    public void beforeTestExecution(ExtensionContext extensionContext) throws Exception {
        getStore(extensionContext).put(START_TIME, System.currentTimeMillis());
    }

    private ExtensionContext.Store getStore(ExtensionContext context) {
        return context.getStore(ExtensionContext.Namespace.create(getClass(), context.getRequiredTestMethod()));
    }
}
